package cp3120.model;

import cp3120.security.SimpleMD5;

import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;

/**
 * A Model of a MD5 Hashed Password.
 *
 * @author Adam Scarr
 */
public class Password {
    private String password;

    /**
     * Public Class Constructor. Converts a string to a password.
     *
     * @param password  The string of the password.
     * @param alreadyHashed If the given password is already in its hashed form (ie pulled from the backing store).
     */
    public Password(String password, boolean alreadyHashed) {
        if (alreadyHashed) {
            this.password = password;
        } else {
            this.password = hashPassword(password);
        }
    }

    /**
     * Public Class Constructor. Converts a string to a password.
     *
     * @param password  The un-hashed password
     */
    public Password(String password) {
        this.password = hashPassword(password);
    }

    /**
     * Empty constructor required for XMLDecoding.
     */
    public Password() {

    }

    public String hashPassword(String password) {
        try {
            return SimpleMD5.MD5(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * Compares two passwords.
     * @param other The password to compare this too.
     * @return  True if the passwords match, otherwise false.
     */
    public boolean equals(Password other) {
        return password.equals(other.password);
    }

    /**
     * Simple Getter.
     *
     * @return a string representation of the hash.
     */
    public String toString() {
        return password;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


}
